<?php
namespace Admin\Controller;

use Think\Exception;
use Admin\Model\EmailListModel;
class IndexController extends CommonController {

    /**
     * 首页
     */
    public function index() {
    	try {
    		$api = D('api')->cache(true)->where('status=1')->select();
            $login_key = getUserName();
    		foreach ($api as $key => $val) {
    			switch ($val['platform']) {
    				case 0:
				    		//c6
							Vendor('C6.C6Api');
							$c6 = new \C6Api($val['api_address']);
                            !S('PendingWorkList'.$login_key)? S('PendingWorkList'.$login_key,$c6->getPendingWorkList(),1800):'';
                            !S('FlatInfoWaitingList'.$login_key)? S('FlatInfoWaitingList'.$login_key,$c6->getFlatInfoWaitingList(),1800):'';
                            !S('C6LoginUrl'.$login_key)? S('C6LoginUrl'.$login_key,$c6->getLoginUrl(),1800):'';

							$this->assign('pending_work_list',S('PendingWorkList'.$login_key));
							$this->assign('flat_info_waiting',S('FlatInfoWaitingList'.$login_key));
				  			$this->assign('c6_login_url',S('C6LoginUrl'.$login_key));
    					break;
					case 1:
							//论坛
                            if(!S('ForumMessageList'.$login_key)):
                                Vendor('Forum.ForumApi');
                                $forum = new \ForumApi($val['api_address']);
                                $messageList = array();
                                foreach ($forum->getForumMessageList(6) as $item) {
                                    $messageList [] = get_object_vars($item);
                                }
                                S('ForumMessageList'.$login_key,$messageList,3600*24);
                                S('ForumLoginUrl'.$login_key,$forum->getLoginUrl(),3600*24);
                            endif;
                            $this->assign('forumMessageList',S('ForumMessageList'.$login_key));
							$this->assign('forum_login_url',S('ForumLoginUrl'.$login_key));
						break;
					case 2:
                            //企业邮箱
                            Vendor('exmail.ExmailApi');
                            $emailListData = array();
                            $emailModel = new EmailListModel();
                            $emailList = $emailModel->getMailApiListByUserId($_SESSION[C('USER_AUTH_KEY')]);
                            $this->assign('emailList',$emailList);
                            //获取不同邮箱后缀的信息
                            foreach ($emailList as $key => $email) :
                                $exmail =   new \ExmailApi($email['agent'],$email['api_key'],$email['mailbox_suffix']);
                                $info = explode('@',$email['email']);

                                if (!S('MailData'.$key.$login_key)) :
                                    S('MailData'.$key.$login_key,$exmail->getMaillLists($info[0]),1800);
                                endif;

                                $mailData = S('MailData'.$key.$login_key);
                                $unread = 0;
                                foreach ($mailData->List as $item) {
                                    if ($item->New){
                                        $unread++;
                                    }
                                }
                                if ($unread != 0)  $emailListData[]['unread'] = $unread;

                                $emailListData[$key]['is_main'] = $email['is_main'];
                                $emailListData[$key]['email_id'] = $email['email_list.id'];
                                $emailListData[$key]['data'] = $mailData->List;
                                $emailListData[$key]['login_url'] = $exmail->getLoginUrl($info[0]);
                            endforeach;

                            $this->assign('emailListData',$emailListData);
						break;
    			}
    		}
            
          /*   //电商中心当月  销售额 订单数量
            $this->assign('etsshop',$this->currencyToggle($this->getSalesReportInfo()));
            //企业中心当月  销售额 订单数量
            $this->assign('enterprise',$this->currencyToggle($this->getSalesReportInfo('03')));

            $saleinfo = $this->currencyToggle($this->getSalesReportBill());
            //电商中心 总销售额
            $this->assign('sales_canvas_data',$saleinfo['total_sales']);

            $ep_saleinfo = $this->currencyToggle($this->getSalesReportBill('03'));
            //企业中心 总销售额
            $this->assign('ep_sales_canvas_data',$ep_saleinfo['total_sales']); */
            

            //电商中心、个小组各个月份销售额，
         //   $this->assign('sales_line_data',$saleinfo['line_data']);

            //电商中心 小组名称
         //   $this->assign('dep_lists',$saleinfo['dep_lists']);

            //企业中心、个小组各个月份销售额，
        //    $this->assign('ep_sales_line_data',$ep_saleinfo['line_data']);
            //企业中心 小组名称
        //    $this->assign('ep_dep_lists',$ep_saleinfo['dep_lists']);
       
            //收藏到首页的网址列表
            $this->assign("conllectLink",$this->getCollectionLink());
            //视频列表
			$this->assign("videolist",$this->getNewVideo());
			//图片列表
			$this->assign("picturelist",$this->getNewPicture());
            //当前单位
           // if (LANG_SET == 'zh-cn') $currency = "￥<%= value %>w";  else $currency = "￥<%= value %>k";
           // $this->assign('currency',$currency);
            //首页报表缓存更新时间
            $last_update_time = $this->getLastUpdateCacheTime();
            $last_update_time = round($last_update_time/3600,2);
            $this->assign('last_update_time',$last_update_time);
            //显示清除缓存按钮
            $this->assign('clear_cache_btn',true);
            //ets返修代办列表
            //$this->assign('ets_rma_list',$this->getEtsRmaList($login_key));
            //$this->assign('ets_login_url',getEtsLoginUrl($login_key));
	    	$this->display();

    	} catch (Exception $e) {
    		$this->error($e->getMessage());
    	}
    }

    /**
     * 获取最近上传的视频
     * @return mixed
     */
    public function getNewVideo()
    {
    	$where['lan']=LANG_SET;
        $title = LANG_SET == 'zh-cn'?'title_cn':'title_en';
        $field = 'youku_url,youtube_url,video_thumbnail,id,'.$title;
    	$list = D("Video")->field($field)->where($where)->limit(6)->order("created_at desc")->select();
    	return $list;
    }
    
    /**
     * 获取最近上传的图片
     * @return mixed
     */
    public function getNewPicture()
    {
        $pictureViewModle = D('PictureFilterView');
        $title = LANG_SET == 'zh-cn'?'title_cn':'title_en';
        $field = 'thumbnail_url,impression_url,origin_url,id,'.$title;
        $where['is_head'] = 1;
        $list = $pictureViewModle->field($field)->where($where)->limit(6)->order("created_at desc")->select();
        return $list;
    }

    /**
     *  个人中心
     */
    public function editProfile() {
        $this->assign('vo',getLoginUserInfo());
        $this->assign('emailSuffix',getEmailSuffix());
        $maillist = new EmailListModel();

        $this->assign('emaillist',$maillist->getMailListByUserId($_SESSION[C('USER_AUTH_KEY')]));
        $this->display();
    }


    /**
     *  保存个人资料
     */
    public  function saveProfile() {
        $data = $_REQUEST;
        /**/
        $maillist = new EmailListModel();
        if ($data['emailaddress'] != array_unique($data['emailaddress'])) {
            $this->error('保存失败!重复邮箱');
        }
        if (count($data['emailaddress'])  && count($data['is_main'])) {
            $hasemail = false;
            foreach ($_REQUEST['email'] as $key => $item) {
                if ($maillist->hasEmail($item,getUserName('','id'))) {
                    $hasemail = true;
                }
            }
            if ($hasemail){
                $this->error('保存失败!该邮箱已经被绑定');
            }
            if ($maillist->updateMailIsMain($data['emailaddress'],$data['is_main']) === false){
                $this->error('保存失败!'.$maillist->getDbError());
            }
        }

        $User = M("user");
        $userid =  $_SESSION[C('USER_AUTH_KEY')];

        if (!empty($_FILES['avatar']['name'])){
            //上传新头像
            $data ['avatar'] =  $this->uploadImage(getAvatarPath());
            //删除以前的头像
            $oldfile = $_SERVER['DOCUMENT_ROOT'].$User->where('id='.$userid)->getField('avatar');
            if( file_exists($oldfile) && is_file( $oldfile ) )
            {
                unlink( $oldfile );
            }
        }

        //保存数据
        if( $User->where('id='.$userid)->save($data) !== false){
            $this->success('保存成功！');
        }else {
           // echo $User->getLastSql();die;
            $this->success('保存失败！'.$User->getDbError());
        }
    	
    }

    /**
     * 获取未发货和已经发货的销售额、订单数量
     * @param string $dep_code   部门编码 07 =》电商中心 03=》企业中心
     * @return mixed  返回对应集合
     *
     */
    public function getSalesReportInfo($dep_code = '07') {
        try{
            $map = array();
            $result = array();
            $nowDate = date('Y-m',time());
            $map['created_at']=array("gt",'2015-01-01');
            $map['department_id'] = array('like',$dep_code.'%');
            $map['order_status'] = array('in',array('pending_shipment','processing','partially_shipped'));
            $map['payment_status'] = array('in',array('verified','pending'));
            
            $map['status'] = array('in',array(1,2));
            $model = D('SalesOrderReportView');

            //获取未发货信息
            $pending_sales_rmb_total =  $model->cache('pending_sales_rmb_total'.$dep_code,3600*24)->where($map)->sum('(qty_ordered-qty_shipped)*rmb_price');

            $result['pending_sales_rmb_total'] = round($pending_sales_rmb_total,3);

//            $pending_sales_qty = $model->cache(true,3600*24)->field('qty_ordered')->where($map)->group('increment_id')->select();
//            if (empty($pending_sales_qty)){
//                $result['pending_sales_qty'] = 0;
//            }else {
//                foreach ($pending_sales_qty as $num) {
//                    $result['pending_sales_qty'] += $num['qty_ordered'];
//                }
//            }

            //获取已发货信息\
            $result['rmb_total'] =  $this->getSalesReportBill($dep_code,date("n"));
//            $sales_qty = $model->cache(true,3600*24)->field('qty_ordered')->where($map)->group('increment_id')->select();
//            if (empty($sales_qty)){
//                $result['sales_qty'] = 0;
//            } else {
//                foreach ($sales_qty as $num) {
//                    $result['sales_qty'] += $num['qty_ordered'];
//                }
//            }
            return $result;

        }catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 单元切换  万和千的切换
     * @param $data
     * @return float
     */
    public function currencyToggle($data){

        if (LANG_SET == 'zh-cn') $ct = 0.0001; else $ct=0.001;

        if ( $data['pending_sales_rmb_total'] ){
            $data['pending_sales_rmb_total'] = round($data['pending_sales_rmb_total']*$ct,1);
            $data['rmb_total'] = round($data['rmb_total']*$ct,1);
        }
        if ($data['total_sales']) {
            $newlist = array();
            foreach ($data['total_sales'] as $item) {
                $newlist [] = round($item*$ct,1);
            }
            $data['total_sales'] = $newlist;
        }
        if (!is_array($data)) {
            $data = round($data*$ct,1);
        }

        return $data;
    }

    /**
     * 按月份获取每个小组的销售额 和当前中心的销售额
     * @param string $dep_code   部门编码 07 =》电商中心 03=》企业中心
     * @return mixed   返回对应集合
     *
     */
    public function getSalesReportBill($dep_code = '07',$month="") {
    //	if (LANG_SET == 'zh-cn') $ct = 0.0001; else $ct=0.001;
        try{
        $model =   D('BillReportView');
        $map['department_id'] = array('like',$dep_code.'%');
        $map['valid_status']=0;
        $datalist = array();
        for ($i=1;$i<=12;$i++) {
            //排除当前月份数据
//            if ($i == date('m',time())){
//                break;
//            }
            $i<10?$num='0'.$i: $num = $i;
            $date = date('Y',time()).'-'.$num;
            $map['bill_date'] = array('like',$date.'%');
            $map['bill_type']=1;

            $a =  $model->cache('sales_report_bill_type1_'.$dep_code.'_'.$i,3600*24)->where($map)->sum("rmb_price*qty");
            $map['bill_type']=2;
            $b =  $model->cache('sales_report_bill_type2_'.$dep_code.'_'.$i,3600*24)->where($map)->sum("rmb_price*qty");
            $data=$a-$b;
            if($month==$i) return round($data,3);
            $countSales[] = round($data,3);
        }
         //   $result['line_data'] = $lineData;       //按月份平分的小组销售额
            $result['total_sales'] = $countSales; //中心销售额
        //    $result['dep_lists'] = $depLists;   //小组名称
             return $result;
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 报表缓存数据的 时间差
     * @return int  时间轴
     */
    public function  getLastUpdateCacheTime() {
        $cachelog = D('cache_log');
        if ($cacheData = $cachelog->find()) {
            $etsshop =  $this->getSalesReportBill('07',date('m',time()));
            $enterprise =  $this->getSalesReportBill('03',date('m',time()));
            if ($cacheData['etsshop'] == $etsshop && $enterprise == $cacheData['enterprise']) {
                return  time() - $cacheData['update_date'];
            }else {
                $newData['etsshop'] = $etsshop;
                $newData['enterprise'] =  $enterprise;
                $newData['update_date'] = time();
                $cachelog->where('id=1')->save($newData);
                return 0;
            }
        } else {
            $cacheData['etsshop'] =  $this->getSalesReportBill('07',date('m',time()));
            $cacheData['enterprise'] =  $this->getSalesReportBill('03',date('m',time()));
            $cacheData['update_date'] = time();
            if ($cachelog->add($cacheData)) return 0;//date('Y-m-d',$cacheData['update_date']);
        }
    }

    /**
     * ets代办返回列表
     * @return mixed
     */
    public function getEtsRmaList($username){

        $map['username']= $username;//getUserName();//.'_'.strtoupper(substr(APP_NAME,0,2));
        $map['flag']=1;
        $list = D("RmaOperator")->order('id desc')->where($map)->limit(10)->select();
        return $list;
    }
    
    /**
     * 首页收藏列表
     * @return mixed
     */
    public function getCollectionLink() {

        $heardMap['header_tag'] = 1;
   //     $Link = M('link')->cache(false)->where($heardMap)->field('id,title,url')->select();
        $heardMap['user_id'] = $_SESSION[C('USER_AUTH_KEY')];
        $favoriteLink = M('favorite')->cache(false)->where($heardMap)->field('id,title,favorite_url')->select();

        $collectLink = array();
        foreach ($favoriteLink as $val){
            $collectLink[] = array(
                'id'    => $val['id'],
                'title' => $val['title'],
                'url'   => $val['favorite_url'],
                'model' => 'favorite'
            );
        }
        return $collectLink;

    }

    /**
     * 删除顶置首页链接
     */
    public function removeFavoritesLink(){
        if ($_REQUEST['model'] && $_REQUEST['id']){
            $model =  D($_REQUEST['model']);
            $data['header_tag'] = 0;
            if ($model->where('id='.$_REQUEST['id'])->save($data) === false){
                $this->error('删除失败： '.$model->getDbError());
            }
        }
        $this->success('删除成功！');
    }

}